#pragma once

#include <QDebug>
#include <QMutex>
#include <QSemaphore>
#include <QThread>

#include "./CanvasWidget.h"

namespace qbe {
class Thread : public QThread {
  Q_OBJECT

 public:
  Thread() {};
  ~Thread() {};

 public:
  static Thread* Instance() {
    static Thread* work = new Thread;
    return work;
  }

  void run(qbe::canvas::CanvasWidget& canvas) {
    auto timer_run = new QTimer(this);
    connect(timer_run, &QTimer::timeout, [&]() {
      if (canvas.app.resource<bool>()) {
        canvas.viewer->handleEvents();
        canvas.app.run();
        canvas.viewer->compile();
        if (canvas.viewer->advanceToNextFrame()) {
          canvas.viewer->update();
          canvas.viewer->recordAndSubmit();
          canvas.viewer->present();
        }
      }
    });
    timer_run->start(33);
  }

  void stopAndWait() {
    m_running = false;
    wait();
    exit();

    deleteLater();
  }

 private:
  bool m_running;
};
}  // namespace qbe